package com.hejun.book.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageInterceptor;
import com.hejun.book.entity.Book;
import com.hejun.book.service.ServiceBook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    ServiceBook serviceBook;

    @GetMapping("/list")
    //先不加分页先查所有
    public String getPage(Model model,
                          @RequestParam(defaultValue = "1") Integer pageNum){
        PageInfo<Book> page=serviceBook.getPage(pageNum);
        model.addAttribute("page",page);
        return "index";
    }

    @GetMapping("/toAddBook")
    public String toAddBook(){
        return "addBook";
    }

    @PostMapping("/addBook")
    public String addBook(@RequestBody Book book,Model model){
        if (serviceBook.add(book)){
            model.addAttribute("message","添加成功");
            System.out.println("添加成功");
        }else {
            return new RuntimeException("添加异常").getMessage();
        }
        return getPage(model,1);
    }
}
